<?php
/**
 * 首页控制器
 * @author jason <yangjs17@yeah.net> 
 * @version TS3.0
 */
class IndexAction extends Action {
	var $classId=0;
	var $Class=array();
	//初始化数据
	protected function _initialize() {
		if( intval($_SESSION['mid'])==0 ) {
			redirect(U('public/Passport/login'));
		}
		if($this->userGroup==5){
			$Class=M("class")->where("admin_id=".$this->mid)->find();
			$this->classId=$Class["class_id"];
			$this->Class=$Class;
		}
	}
	/**
	 * 我的首页
	 *
	 * @return void
	 */
	public function test() {
		$sql = 'select t.id,s.stu_id,t.name,s.stu_name,t.gender,s.gender,t.birth_date,s.birthday from '.C('DB_PREFIX').'table4 t join '.C('DB_PREFIX').'student s on s.stu_name=t.name  ';
		
        $student = M()->query($sql);
		foreach ($student as $key => $value) {
			if($value["name"]==$value["stu_name"] && $value["birthday"]==$value["birth_date"] && $value["stu_id"]==$value["stu_id"]){
				$_map=array(
					'old_student'=>$value['id'],
					'new_student'=>$value['stu_id'],
				);
				if(!M("stu_data")->where($_map)->find()){
					M("stu_data")->add($_map);
					dump(M("stu_data")->getLastSql());
				}
			}
		}
	}
	public function index() {
		$this->display();
	}

	public function addClass(){
		$this->display();
	}
	//添加班级
	public function doAddClass(){
		$user=$this->user;
		$email=$user["email"]."-".getAllLetter($_POST["class_name"]);
		$class_name=$_POST["class_name"];
		if( $count = M("user")->where("is_del=0 and email='".$email."'")->count() ){
			$email = $email.$count;
		}
		$school=M("school")->where("fid=".$this->mid)->find();
		$login_salt=rand(10000, 99999);
		$data=array(
			'uname'=>$class_name,
			'email'=>$email,
			'pwd'=>$_POST["pwd"],
			'province'=>$user["province"],
			'city'=>$user["city"],
			'area'=>$user["area"],
			'fid'=>$this->mid,
			'login_salt'=>$login_salt,
			'password'=>md5 (md5($_POST["pwd"]).$login_salt),
			'ctime'=>time(),
			'no_login'=>1,
			'permissions'=>1,
		);
		$res=M("user")->add($data);
		if($res){
			unset($data);
			$map=array(
				'uid'=>$res,
				'user_group_id'=>5,
			);
			$data=array(
				'class_grade'=>$_POST["class_grade"],
				'school_id'=>$school["id"],
				'class_name'=>$class_name,
				'class_type'=>intval($_POST["class_type"]),
				'admin_id'=>$res,
				'ctime'=>time(),
			);
			M("user_group_link")->add($map);
			M("class")->add($data);
			echo $res;exit();
		}else{
			echo "操作失败";exit();
		}
	}
	//修改班级信息
	public function UpdateClass(){
		$class_id=intval($_GET["id"]);
		$data = M("class")->where("class_id=".$class_id)->find();

		if( $data['is_up'] == 1 ) {
    		if($data['class_name1']) {
				$data['class_name'] = $data['class_name1'];
			} else {
				$data['class_name'] = $data['class_name'];
			}
		} 

		if( $data['is_up'] == 2 ){
			if($data['class_name2']) {
				$data['class_name'] = $data['class_name2'];
			} else {
				$data['class_name'] = $data['class_name1'];
			}
		}

		$user=M("user")->where("uid=".$data["admin_id"])->field("pwd,uid")->find();
		$data["pwd"]=$user["pwd"];
		$this->assign("data",$data);
		$this->display("");
	}
	//修改班级信息（操作）
	public function doUpdateClass(){
		$id=intval($_POST["id"]);
		$uid=intval($_POST["uid"]);
		$login_salt=rand(10000, 99999);
		$user  = $this->user;
		$email = $user["email"]."-".getAllLetter($_POST["class_name"]);
		if( $count = M("user")->where("is_del=0 and email='".$email."'")->count() ){
			$email = $email.$count;
		}
		$map=array(
			'uname'=>$_POST["class_name"],
			'pwd'=>$_POST["pwd"],
			'login_salt'=>$login_salt,
			'email'     =>$email,
			'password'=>md5 (md5($_POST["pwd"]).$login_salt),
		);
		if( M("user")->where('uname='."{$_POST['class_name']}")->find() ) {
			echo "名称重复，请更换";exit();
		}
		$res=M("user")->where("uid=".$uid)->save($map);
		if($res){
			model('User')->cleanCache($uid);
			$is_up = M("class")->where("class_id=".$id)->getField('is_up');
			if($is_up == 0) {
				$data['class_name'] = $_POST["class_name"];
			} elseif ($is_up == 1) {
				$data['class_name1'] = $_POST["class_name"];
			} else {
				$data['class_name2'] = $_POST["class_name"];
			}
			$data['class_type'] = $_POST["class_type"];
			$data['class_grade'] = $_POST["class_grade"];
			
			M("class")->where("class_id=".$id)->save($data);
			echo $res;exit();
		}else{
			echo "修改失败,请重试！";exit();
		}
	}

	//升班级
	public function upgrade(){
	    //班级id，以逗号的形式隔开的
	    $ids = $_POST['ids'];
		$school = M("school")->where("fid=".$this->mid)->find();
    	$map=array(
    		'school_id'=>$school['id'],
    		'is_del'=>0
    	);
    	$classIdArr = explode(',',$ids);
    	$map['class_id'] = array('IN',$classIdArr);
        $map["class_type"] = intval($_POST["class_type"]);
        $data = M("class")->where($map)->findAll();
        foreach ($data as $key => &$val) {
        	$_data['class_type']  = $val['class_type'] - 1;
			$_data['is_up']       = $val['is_up'] + 1;
			$rs = M('class')->where('class_id='.$val['class_id'])->save($_data);
        }
		
		if($rs !== false){
			echo $rs;exit;
		} else {
			echo "升班失败，请重试！";exit();
		}

	}

	//毕业
    public function Graduation()
    {
        //班级id
        $id=intval($_POST["id"]);
        $res = M("class")->where("class_id=".$id)->save(['is_graduation'=>1]);
        if($res){
            echo $res;exit();
        }else{
            echo "毕业操作失败！";exit();
        }
	}

    //撤销毕业
    public function revocation_graduation()
    {
        //班级id
        $id=intval($_POST["id"]);
        $res = M("class")->where("class_id=".$id)->save(['is_graduation'=>0]);
        if($res){
            echo $res;exit();
        }else{
            echo "撤销毕业操作失败！";exit();
        }
    }
	//删除班级（操作）
	public function DeleteClass(){
		$id=intval($_POST["id"]);
		$admin_id=intval($_POST["admin_id"]);
		$type=intval($_POST["type"]);
		$map['is_del']=$type;
		if($type==1){
			//删除相应的学生信息
			/*$stu_ids=M("student")->where("class_id=".$id)->field("stu_id")->select();
			if($stu_ids){
				foreach ($stu_ids as $key => $value) {
					$test_data=M("test_data")->where("stu_id=".$value["stu_id"])->select();
					if($test_data){
						foreach ($test_data as $k => $v) {
							M("report_data")->where("tid=".$v["test_id"])->delete();
							M("test_data")->where("test_id=".$v["test_id"])->delete();
						}
					}
					M("health_report")->where("type=5 and fid=".$value["stu_id"])->delete();
				}
			}
			M("student")->where("class_id=".$id)->delete();
			//删除相应的报告信息
			$health_report=M("health_report")->where("type=4 and fid=".$admin_id)->select();
			if($health_report){
				foreach ($health_report as $key => $value) {
					M("report_data")->where("rpt_id=".$value["rpt_id"])->delete();
					M("health_report")->where("rpt_id=".$value["rpt_id"])->delete();
				}
			}
			//删除相应的账户信息
			M("user")->where("uid=".$admin_id)->delete();
			M("user_group_id")->where("uid=".$admin_id)->delete();
			*/
			$res=M("class")->where("class_id=".$id)->save($map);
			if($res){
				echo $res;exit();
			}else{
				echo "删除失败，请重试！";exit();
			}
		}else{
			$res=M("class")->where("class_id=".$id)->save($map);
			if($res){
				$data['is_del'] = 1;
				M("user")->where("uid=".$admin_id)->save($data);
				echo $res;exit();
			}else{
				echo "删除失败，请重试！";exit();
			}
		}
	}


	public function recoveryClass() {
		$this->display();
	}

    //还原班级（操作）
    public function RestoreClass(){
        $id=intval($_POST["id"]);
        $admin_id=intval($_POST["admin_id"]);
        $type=intval($_POST["type"]);
        $map['is_del']=$type;
        if($type==1){
            $res=M("class")->where("class_id=".$id)->save($map);
            if($res){
                echo $res;exit();
            }else{
                echo "删除失败，请重试！";exit();
            }
        }else{
            $res=M("class")->where("class_id=".$id)->save($map);
            if($res){
                $data['is_del'] = 1;
                M("user")->where("uid=".$admin_id)->save($data);
                echo $res;exit();
            }else{
                echo "删除失败，请重试！";exit();
            }
        }
    }
	//学生调档操作
	public function UpdateStuClass(){
		$stu_id=intval($_POST["stu_id"]);
		$data["class_id"]=intval($_POST["class_id"]);
		$res=M("student")->where("stu_id=".$stu_id)->save($data);
		if($res){
			echo $res;exit();
		}else{
			echo "修改失败，请重试！";exit();
		}
	}
	//获取学生信息
	public function Student(){
		$params['grade'] = $_GET["grade"];
		$params['class'] = $_GET["class"];
		$params['stuName'] = $_GET["stuName"];

		$where['is_del']=0;
		if($this->classId>0){
			$where["school_id"]=$this->Class["school_id"];
		}else{
			$school=M("school")->where("fid=".$this->mid)->find();
			$where["school_id"]=$school["id"];
		}
		$where['class_type'] = array('gt' , 0);
		$data=M("class")->where($where)->findAll();
        foreach ($data as &$val) {
            if($val['is_up'] == 1) {
                $val['class_name'] = $val['class_name1'];
            } elseif($val['is_up'] == 2) {
                $val['class_name'] = $val['class_name2'];
            }  
        }
        
		$this->assign("class_id",$this->classId);
		$this->assign("data",$data);
		$this->assign("params",$params);
		$this->display();
	}

	//获取学生信息
	public function recoveryStudent(){
		$params['grade'] = $_GET["grade"];
		$params['class'] = $_GET["class"];
		$params['stuName'] = $_GET["stuName"];

		$where['is_del']=1;
		if($this->classId>0){
			$where["school_id"]=$this->Class["school_id"];
		}else{
			$school=M("school")->where("fid=".$this->mid)->find();
			$where["school_id"]=$school["id"];
		}
		$where['class_type'] = array('gt' , 0);
		$data=M("class")->where($where)->findAll();
        foreach ($data as &$val) {
            if($val['is_up'] == 1) {
                $val['class_name'] = $val['class_name1'];
            } elseif($val['is_up'] == 2) {
                $val['class_name'] = $val['class_name2'];
            }  
        }
        
		$this->assign("class_id",$this->classId);
		$this->assign("data",$data);
		$this->assign("params",$params);
		$this->display();
	}

    //获取删除的学生信息
    public function RestoreStudent(){
        $params['grade'] = $_GET["grade"];
        $params['class'] = $_GET["class"];
        $params['stuName'] = $_GET["stuName"];

        $where['is_del']=1;
        if($this->classId>0){
            $where["school_id"]=$this->Class["school_id"];
        }else{
            $school=M("school")->where("fid=".$this->mid)->find();
            $where["school_id"]=$school["id"];
        }
        $where['class_type'] = array('gt' , 0);
        $data=M("class")->where($where)->findAll();
        foreach ($data as &$val) {
            if($val['is_up'] == 1) {
                $val['class_name'] = $val['class_name1'];
            } elseif($val['is_up'] == 2) {
                $val['class_name'] = $val['class_name2'];
            }
        }

        $this->assign("class_id",$this->classId);
        $this->assign("data",$data);
        $this->assign("params",$params);
        $this->display();
    }

	//添加学生操作
	public function addStudent(){
		if($this->classId>0){
			$class=M("class")->where("admin_id=".$this->mid)->find();
			$class_id = $class['class_id'];
	        if($class["class_type"]==1){
	            if( M('class')->where( array('class_id'=>$class_id,'class_name' => array('like' ,'%大%班%') ) )->find() ) {
	                $class['class_name'] = $class['class_name'];
	            }
	            if( M('class')->where( array('class_id'=>$class_id,'class_name1' =>  array('like' ,'%大%班%') ) )->find() ) {
	                $class['class_name'] = $class['class_name1'];
	            }
	            if( M('class')->where( array('class_id'=>$class_id,'class_name2' =>  array('like' ,'%大%班%') ) )->find() ) {
	                $class['class_name'] = $class['class_name2'];
	            }
	        }else if($class["class_type"]==2){
	            if( M('class')->where( array('class_id'=>$class_id,'class_name' =>  array('like' ,'%中%班%') ) )->find() ) {
	                $class['class_name'] = $class['class_name'];
	            }
	            if( M('class')->where( array('class_id'=>$class_id,'class_name1' =>  array('like' ,'%中%班%') ) )->find() ) {
	                $class['class_name'] = $class['class_name1'];
	            }
	            if( M('class')->where( array('class_id'=>$class_id,'class_name2' =>  array('like' ,'%中%班%') ) )->find() ) {
	                $class['class_name'] = $class['class_name2'];
	            }
	        }else if($class["class_type"]==3){
	            if( M('class')->where( array('class_id'=>$class_id,'class_name' =>  array('like' ,'%小%班%') ) )->find() ) {
	                $class['class_name'] = $class['class_name'];
	            }
	            if( M('class')->where( array('class_id'=>$class_id,'class_name1' =>  array('like' ,'%小%班%') ) )->find() ) {
	                $class['class_name'] = $class['class_name1'];
	            }
	            if( M('class')->where( array('class_id'=>$class_id,'class_name2' =>  array('like' ,'%小%班%') ) )->find() ) {
	                $class['class_name'] = $class['class_name2'];
	            }
	        }else{
	            $class['class_name'] = $class['class_name'];
	        }

			$this->assign("class",$class);
		}
		$this->display();
	}
	//修改学生
	public function UpdateStudent(){
		$id=intval($_GET["id"]);
		$params['grade'] = $_GET["grade"];
		$params['class'] = $_GET["class"];
		$params['stuName'] = $_GET["stuName"];
		$data=M("student")->where("stu_id=".$id)->find();
		$this->assign("data",$data);
		$this->assign("params",$params);
		$this->display();
	}
	//修改学生(操作)
	public function doSaveStudent(){
		$id=intval($_POST["id"]);
		$class_id=intval($_POST["class_id"]);
		$class=M("class")->where("class_id=".$class_id)->find();
		$data=array(
			'stu_name'=>$_POST["stu_name"],
			'birthday'=>$_POST["birthday"],
			'birth_weight'=>$_POST["birth_weight"],
			'into_campus_time'=>$_POST["into_campus_time"],
			'class_id'=>$class_id,
			'school_id'=>$class['school_id'],
			'gender'=>intval($_POST["gender"]),
			'birth_condition'=>intval($_POST["birth_condition"]),
			'admin_id'=>$this->mid
		);
		$res= $id>0 ? M("student")->where("stu_id=".$id)->save($data) : M("student")->add($data);
		if($res){
			echo $res;exit();
		}else{
			echo "操作失败，请重试";exit();
		}
	}
	//删除学生（操作）
	public function DeleteStu(){
		$id=intval($_POST["id"]);
		$test_data=M("test_data")->where("is_del=0 and stu_id=".$id)->select();
		if($test_data){
			foreach ($test_data as $key => $value) {
				//M("report_data")->where("tid=".$value["test_id"])->delete();
				M("test_data")->where("test_id=".$value["test_id"])->save( array('is_del'=>1) );
			}
		}
		//M("health_report")->where("type=5 and fid=".$id)->delete();
		$res=M("student")->where("stu_id=".$id)->save( array('is_del'=>1) );
		if($res){
			echo $res;exit();
		}else{
			echo "删除失败，请重试！";exit();
		}
	}

    //还原学生（操作）
    public function RestoreStu(){
        $id=intval($_POST["id"]);
        $test_data=M("test_data")->where("is_del=1 and stu_id=".$id)->select();
        if($test_data){
            foreach ($test_data as $key => $value) {
                //M("report_data")->where("tid=".$value["test_id"])->delete();
                M("test_data")->where("test_id=".$value["test_id"])->save( array('is_del'=>0) );
            }
        }
        //M("health_report")->where("type=5 and fid=".$id)->delete();
        $res=M("student")->where("stu_id=".$id)->save( array('is_del'=>0) );
        if($res){
            echo $res;exit();
        }else{
            echo "删除失败，请重试！";exit();
        }
    }
    /**
     * 取得班级列表
     * @param boolean $return 是否返回数据，如果不是返回，则会直接输出Ajax JSON数据
     * @return void|array
     */
    public function getClassList() {
    	$school=M("school")->where("fid=".$this->mid)->find();
    	$map=array(
    		'school_id'=>$school['id'],
    		'is_del'=>0
    	);
        $class_type=intval($_GET["class_type"]);
        if($class_type){
            $map["class_type"]=$class_type;
        }
        $user = $this->user;
        $data = M("class")->where($map)->findPage(20);
        foreach ($data['data'] as &$value) {
        	$value['user']=M('user')->where("uid=".$value['admin_id'])->field("email,pwd,uid")->find();
        	//$value['user']['email'] = $user['email'];
        	if( $value['is_up'] == 1 ) {
        		if($value['class_name1']) {
					$value['class_name'] = $value['class_name1'];
				} else {
					$value['class_name'] = $value['class_name'];
				}
			} 

			if( $value['is_up'] == 2 ){
				if($value['class_name2']) {
					$value['class_name'] = $value['class_name2'];
				} else {
					$value['class_name'] = $value['class_name1'];
				}
			}
        }
        if ($data['data']) {
            $this->assign('listData', $data['data']);
            $this->assign('class_type',$class_type);
            $html = $this->fetch('index_list');
        } else {
            $html = $this->fetch('index_list');
        }
        $data['data'] = $html;
        echo json_encode($data);
        exit();
    }
    /**
     * 取得学生数据（通过班级id）
     * @param boolean $return 是否返回数据，如果不是返回，则会直接输出Ajax JSON数据
     * @return void|array
     */
    public function getStudentList() {
        $stu_name=$_GET["stu_name"];
        $class_id=intval($_GET["class_id"]);
        $map["is_del"]=0;
        $class_id && $map['class_id']=$class_id;
        if($stu_name){
            $map["stu_name"]=array("like","%".$stu_name."%");
        }
        $data = M("student")->where($map)->findPage(20);
        if ($data['data']) {
            $this->assign('listData', $data['data']);
            $this->assign('stu_name',$stu_name);
            $this->assign('class_id',$class_id);
            $html = $this->fetch('Student_list');
        } else {
            $html = $this->fetch('Student_list');
        }
        $data['data'] = $html;
        echo json_encode($data);
        exit();
    }

    /**
     * 取得删除的学生数据（通过班级id）
     * @param boolean $return 是否返回数据，如果不是返回，则会直接输出Ajax JSON数据
     * @return void|array
     */
    public function getDelStudentList() {
        $stu_name=$_GET["stu_name"];
        $class_id=intval($_GET["class_id"]);
        $map["is_del"]=1;
        $class_id && $map['class_id']=$class_id;
        if($stu_name){
            $map["stu_name"]=array("like","%".$stu_name."%");
        }
        $data = M("student")->where($map)->findPage(20);
        if ($data['data']) {
            $this->assign('listData', $data['data']);
            $this->assign('stu_name',$stu_name);
            $this->assign('class_id',$class_id);
            $html = $this->fetch('recoveryStudentList');
        } else {
            $html = $this->fetch('recoveryStudentList');
        }
        $data['data'] = $html;
        echo json_encode($data);
        exit();
    }

    /**
     * 取得删除的班级列表
     * @param boolean $return 是否返回数据，如果不是返回，则会直接输出Ajax JSON数据
     * @return void|array
     */
    public function getDelClassList() {
        $school=M("school")->where("fid=".$this->mid)->find();
        $map=array(
            'school_id'=>$school['id'],
            'is_del'=>1
        );
        $class_type=intval($_GET["class_type"]);
        if($class_type){
            $map["class_type"]=$class_type;
        }
        $user = $this->user;
        $data = M("class")->where($map)->findPage(20);
        foreach ($data['data'] as &$value) {
            $value['user']=M('user')->where("uid=".$value['admin_id'])->field("email,pwd,uid")->find();
            //$value['user']['email'] = $user['email'];
            if( $value['is_up'] == 1 ) {
                if($value['class_name1']) {
                    $value['class_name'] = $value['class_name1'];
                } else {
                    $value['class_name'] = $value['class_name'];
                }
            }

            if( $value['is_up'] == 2 ){
                if($value['class_name2']) {
                    $value['class_name'] = $value['class_name2'];
                } else {
                    $value['class_name'] = $value['class_name1'];
                }
            }
        }
        if ($data['data']) {
            $this->assign('listData', $data['data']);
            $this->assign('class_type',$class_type);
            $html = $this->fetch('recoveryClassList');
        } else {
            $html = $this->fetch('recoveryClassList');
        }
        $data['data'] = $html;
        echo json_encode($data);
        exit();
    }
}	           
